package com.rakuten.api.mule.transformers;

import java.util.Iterator;
import java.util.Map;

import org.mule.api.transformer.TransformerException;
import org.mule.config.i18n.MessageFactory;
import org.mule.transformer.AbstractTransformer;
import org.mule.transformer.types.SimpleDataType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MapToQueryParametersTransformer extends AbstractTransformer {
    private final static Logger logger = LoggerFactory.getLogger(MapToQueryParametersTransformer.class);
	
    public MapToQueryParametersTransformer() {
	registerSourceType(new SimpleDataType<Map<String,String>>(Map.class));
	//registerSourceType(new SimpleDataType<Object>(Object.class));

	setReturnDataType(new SimpleDataType<String>(String.class));
    }

    @Override
    protected Object doTransform(Object src, String enc)
	throws TransformerException {

    	String params="";	
	try {
	    Map m = (Map)src;


	    String sep = null;
	    boolean flag = false;
	    for (Iterator it = m.entrySet().iterator(); it.hasNext(); ) {
	        Map.Entry entry = (Map.Entry)it.next();
	        String key = (String)entry.getKey();
	        //System.out.println("key = "+key);
	        String value = null;
	        if (entry.getValue() instanceof String) {
	        	value = (String)entry.getValue();
	        } else {
	        	value = Integer.toString((Integer)entry.getValue());
	        }

		if (flag==false) {
		    sep = "?";
		    flag = true;
		} else {
		    sep = "&";
		}
		params += sep+key+"="+ value;
	    }
	    logger.debug("" + src.getClass());
		
	} catch (Exception e) {
		e.printStackTrace();
	    throw new TransformerException(MessageFactory.createStaticMessage(e.getMessage()));
	}
	return params;
    }
}
